package san.service.dictionary;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.utils.Page;
import san.dao.dictionary.DictionaryDao;
import san.entity.dictionary.Dictionary;

@Service("dictionaryService")
@Transactional
public class DictionaryService {
	/**
	 * 自动生成DictionaryService类.
	 */
	@Autowired
	private DictionaryDao dictionaryDao;

	@Transactional(readOnly = true)
	public Page<Dictionary> getAll(Page<Dictionary> page) {
		return dictionaryDao.getAll(page);
	}

	@Transactional(readOnly = true)
	public Dictionary get(String id) {
		return dictionaryDao.get(id);
	}

	public void save(Dictionary dictionary) throws NoSuchMethodException {
		dictionaryDao.save(dictionary);
	}

	public void delete(String id) {
		dictionaryDao.delete(id);
	}

	/**
	 * 得到字典表的根对象.
	 */
	public Dictionary getDictionaryRoot() throws Exception {
		Dictionary dictionary = dictionaryDao.getDictionaryRoot();
		if(dictionary==null){
			return null;
		}
		dictionary = setDictionarySon(dictionary);
		if (dictionary.getSon() != null) {
			for (Dictionary son : dictionary.getSon()) {
				son = setDictionarySon(son);
				if (son.getSon() != null) {
					for (Dictionary grandson : son.getSon()) {
						grandson = setDictionarySon(grandson);
					}
				}
			}
		}
		return dictionary;
	}

	public Dictionary setDictionarySon(Dictionary dictionary) throws Exception {
		List<Dictionary> dictionaryList = dictionaryDao.findBy("parentId",
				dictionary.getId());
		dictionary.setSon(dictionaryList);
		return dictionary;
	}
}
